package com.zyg.apart.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyg.apart.mapper.UserMapper;
import com.zyg.apart.model.Role;
import com.zyg.apart.model.User;
import com.zyg.apart.service.UserService;
import com.zyg.apart.util.Const;
import com.zyg.apart.util.MD5Util;
import com.zyg.apart.view.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean login(LoginUser loginUser, HttpServletRequest request) {
        User user = userMapper.selectByName(loginUser.getUsername());
        if (user != null) {
            System.out.println(MD5Util.getMD5ByCul(loginUser.getPwd()));
            if (user.getState() == 0 && user.getPwd().equals(MD5Util.getMD5ByCul(loginUser.getPwd()))) {
                HttpSession session = request.getSession();
                session.setAttribute("u", user);
                return true;
            }
        }
        return false;
    }

    @Override
    public Role getRoleByName(String username) {
        return userMapper.getRoleByName(username);
    }

    @Override
    public Map<String,Object> getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public int editUser(User user) {
        return userMapper.editUser(user);
    }

    @Override
    public int addUser(User user) {
        user.setCreate_time(new Date());
        String data = MD5Util.getMD5ByCul(user.getPwd());
        user.setPwd(data);
        return userMapper.addUser(user);
    }

    @Override
    public PageInfo<Map<String, Object>> getAllUsers(Integer currentPage) {
        PageHelper.startPage(currentPage, Const.pageSize);
        List<Map<String,Object>> list = userMapper.getAllUsers();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int delUserById(Integer id) {
        return userMapper.delUserById(id);
    }
}
